package com.atg.atgchat.init.common.event.listener;

import com.atg.atgchat.init.common.event.UserLoginEvent;
import com.atg.atgchat.init.user.dao.UserDao;
import com.atg.atgchat.init.user.model.entity.User;
import com.atg.atgchat.init.user.model.enums.UserActivateStatusEnum;
import com.atg.atgchat.init.user.service.IpService;
import com.atg.atgchat.init.websocket.model.enums.UserActiveStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import javax.annotation.Resource;

/*
author: atg
time: 2025/1/17 15:53
*/
@Slf4j
@Component
public class UserLoginListener implements ApplicationListener<UserLoginEvent> {


    @Resource
    private UserDao userDao;
    @Resource
    private IpService ipService;


    @Override
    @Async
    public void onApplicationEvent(UserLoginEvent event) {
        User user = event.getUser();
        // 确保IpInfo不为null
        if (user.getIpInfo() == null) {
            log.error("IpInfo is null for user: {}", user.getId());
            return;
        }
        User UpdateUser = new User();
        UpdateUser.setId(user.getId());
        UpdateUser.setLastOptTime(user.getLastOptTime());
        UpdateUser.setIpInfo(user.getIpInfo());
        UpdateUser.setStatus(UserActivateStatusEnum.ONLINE.getStatus());
        boolean b = userDao.updateById(UpdateUser);
        if (!b) {
            log.error("更新用户信息失败");
        }
        // ip 信息保存成功后，再发送消息给前端---ip解析
        ipService.refreshIpDetail(user.getId());

    }
}
//    @Async
////    @TransactionalEventListener(classes = UserLoginEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
//    @EventListener(classes = UserLoginEvent.class)
//    public void SavaIpEvent(UserLoginEvent event) {
//
//    }

//@Component
//public class UserLoginListener {
//
//    @Autowired
//    private IpService ipService;
//    @Autowired
//    private UserDao userDao;
//
//    @Async
//    @TransactionalEventListener(classes = UserLoginEvent.class, phase = TransactionPhase.AFTER_COMMIT,fallbackExecution=true)
//    public void saveDB(UserLoginEvent event) {
//        User user = event.getUser();
//
//        User update = new User();
//        update.setId(user.getId());
//        update.setLastOptTime(user.getLastOptTime());
//        update.setIpInfo(user.getIpInfo());
//        update.setActiveStatus(UserActiveStatusEnum.ONLINE.getStatus());
//        userDao.updateById(update);
//        //用户ip详情的解析
//        ipService.refreshIpDetail(user.getId());
//    }
//}
